import {listen} from "@tauri-apps/api/event";
import {messageMapSave} from "../actions/message_map_save.ts";
import {addListener} from "../actions/listeners.ts";
import {getCurrentWindow} from "@tauri-apps/api/window";

export const receiveMessage = async () => {
    let main = getCurrentWindow();
    await main.listen<String>("receive-message", (event) => {
        let data = event.payload;
        let jsonData: object = JSON.parse(data);
        let contentBytes = jsonData["content"];
        const decoder = new TextDecoder('utf-8');
        let content: string = decoder.decode(new Uint8Array(contentBytes));
        if (jsonData["message_type"] === "File"){
            content = JSON.parse(content);
        }
        content = content.replace(/^"|"$/g, '');
        let msg = {
            sender_account: jsonData["sender_account"],
            to_account: jsonData["to_account"],
            message_type: jsonData["message_type"],
            content: content,
        };
        messageMapSave(msg,false);
        console.log("receive-message event received a message type:" + msg.message_type);
    }).then((unListenFn) => {
        addListener(unListenFn);
    });
};